package com.hpq.common.config;

import com.hpq.user.service.handler.LogHandler;
import com.hpq.user.service.handler.MsgHandler;
import com.hpq.user.service.handler.ScanHandler;
import com.hpq.user.service.handler.SubscribeHandler;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

import static me.chanjar.weixin.common.api.WxConsts.EventType.SCAN;
import static me.chanjar.weixin.common.api.WxConsts.EventType.SUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType.EVENT;

@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
public class WxMpConfig {
    private final LogHandler logHandler;
    private final SubscribeHandler subscribeHandler;
    private final ScanHandler scanHandler;
    private final MsgHandler msgHandler;
    private final WxMpProperties properties;

    /**
     * 初始化 WxMpService
     * @return
     */
    @Bean
    public WxMpService wxMpService() {
    final List<WxMpProperties.MpConfig> configs = this.properties.getConfigs();
    if(configs == null){
        throw new IllegalArgumentException("No WxMpConfig found, please check your configuration.");
    }
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setMultiConfigStorages(
            configs.stream().map(a->{
                WxMpDefaultConfigImpl configStorage;
                configStorage = new WxMpDefaultConfigImpl();
                configStorage.setAppId(a.getAppId());
                configStorage.setSecret(a.getAppSecret());
                configStorage.setToken(a.getToken());
                configStorage.setAesKey(a.getAesKey());
                return configStorage;
            }).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a->a,(a, b)->a)));
        return wxMpService;
    }
    /**
     *设置消息处理规则
     */
    @Bean
    public WxMpMessageRouter wxMpMessageRouter() {
       final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService());
       //记录所有事件的日志(异步执行)
        newRouter.rule().handler(this.logHandler).next();
        //关注事件
        newRouter.rule().async(false).msgType(EVENT).event(SUBSCRIBE).handler(this.subscribeHandler).end();
        //扫码事件
        newRouter.rule().async(false).msgType(EVENT).event(SCAN).handler(this.scanHandler).end();
        //默认
        newRouter.rule().async(false).handler(this.msgHandler).end();
        return newRouter;
    }
}
